﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Data;

namespace Library.DAL
{
    public class BaseController
    {
        //propriedades
        private OleDbDataAdapter dAdapt;
        private OleDbCommandBuilder commandBuilder;
        private string tableName = String.Empty;
        
        public BaseController(string tableName)
        {
            this.tableName = tableName;

            configureAdapter();
        }

        /// <summary>
        /// Configura o data adapter para que os comandos básicos 
        /// de recuperação de dados sejam criados
        /// </summary>
        private void configureAdapter()
        {
            this.dAdapt = new OleDbDataAdapter("SELECT * FROM " + tableName.ToUpper().ToString(), Library.Properties.Settings.Default.connectionString);
            this.commandBuilder = new OleDbCommandBuilder(dAdapt);
        }

        private void configureCustomAdapter(string selectStatement)
        {
            this.dAdapt.SelectCommand.CommandText = selectStatement;
        }

        /// <summary>
        /// Retorna todos os registros da tabela
        /// </summary>
        /// <returns></returns>
        public DataTable getAllRecords()
        {
            this.configureAdapter();
            return getRecords();            
        }

        /// <summary>
        /// Retorna os dados solicitados no statement (Query)
        /// </summary>
        /// <returns></returns>
        private DataTable getRecords()
        {
            DataTable dt = new DataTable(tableName.ToUpper());
            dAdapt.Fill(dt);
            return dt;
        }

        /// <summary>
        /// Efetua Update na tabela com os dados modificados
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public bool UpdateDataTable(DataTable dt)
        {
            try
            {
                this.configureAdapter();
                dAdapt.Update(dt);
            }
            catch (Exception erro)
            {
                throw new Exception("Erro ao efetuar atualização do banco de dados:\n" + erro.Message);
            }
            
            return true;
        }

        /// <summary>
        /// Retorna dados passados pelo statement
        /// </summary>
        /// <param name="selectStatement"></param>
        /// <returns></returns>
        protected DataTable executeQuery(string selectStatement)
        {
            this.configureCustomAdapter(selectStatement);
            return this.getRecords();
        }
    }
}
